<template>
    <div class="app-container">
        <el-form :model="main.queryParams" size="small" :inline="true" v-show="main.showSearch">
            <el-form-item label="本地订单号" prop="orderCode">
                <el-input v-model="main.queryParams.orderCode" placeholder="请输入本地订单号" />
            </el-form-item>
            <el-form-item label="渠道订单号" prop="eOrderCode">
                <el-input v-model="main.queryParams.eOrderCode" placeholder="请输入渠道订单号" />
            </el-form-item>
            <el-form-item label="客人姓名" prop="names">
                <el-input v-model="main.queryParams.names" placeholder="请输入客人姓名" />
            </el-form-item>
            <el-form-item label="选择酒店" prop="hotelName">
                <el-select v-model="main.queryParams.hotelId" filterable placeholder="请选择" clearable>
                    <el-option v-for="item in main.hotelListAll" :key="item.hotelId" :label="item.hotelName"
                        :value="item.hotelId">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="支付日期" prop="paymentDate">
                <el-date-picker v-model="main.queryParams.paymentDate" value-format="yyyy-MM-dd" type="daterange"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="支付状态" prop="zfzt">
                <el-select v-model="main.queryParams.zfzt" placeholder="请选择支付状态" clearable>
                    <el-option v-for="dict in dict.type.el_zfzt" :key="dict.value" :label="dict.label"
                        :value="dict.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="支付渠道" prop="zfqd">
                <el-select v-model="main.queryParams.zfqd" placeholder="请选择支付渠道" clearable>
                    <el-option v-for="dict in dict.type.el_zfqd" :key="dict.value" :label="dict.label"
                        :value="dict.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="返款渠道" prop="fkqd">
                <el-select v-model="main.queryParams.fkqd" placeholder="请选择返款渠道" clearable>
                    <el-option v-for="dict in dict.type.el_fkqd" :key="dict.value" :label="dict.label"
                        :value="dict.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="支付金额" prop="paymentPrice">
                <el-input v-model="main.queryParams.paymentPrice" placeholder="请输入支付金额" />
            </el-form-item>
            <el-form-item label="销售单类型" prop="xsdlx">
                <el-select v-model="main.queryParams.xsdlx" placeholder="请选择销售单类型" clearable>
                    <el-option v-for="dict in dict.type.el_xsdlx" :key="dict.value" :label="dict.label"
                        :value="dict.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="返款状态" prop="refundStatus">
                <el-select v-model="main.queryParams.refundStatus" placeholder="请选择返款状态" clearable>
                    <el-option v-for="dict in dict.type.el_fkzt" :key="dict.value" :label="dict.label"
                        :value="dict.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="采购价" prop="cgj">
                <el-input v-model="main.queryParams.cgj" placeholder="请输入采购价" />
            </el-form-item>
            <el-form-item label="入住日期" prop="startTime">
                <el-date-picker v-model="main.queryParams.startTime" value-format="yyyy-MM-dd" type="daterange"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="离店日期" prop="endTime">
                <el-date-picker v-model="main.queryParams.endTime" value-format="yyyy-MM-dd" type="daterange"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="返款日期" prop="refundDate">
                <el-date-picker v-model="main.queryParams.refundDate" value-format="yyyy-MM-dd" type="daterange"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="clearQueryParams">重置</el-button>
                <el-button type="primary" plain icon="el-icon-plus" @click="openAddRegister" size="mini">新增</el-button>
                <el-button type="success" size="mini" icon="el-icon-money" @click="openPayment">支付</el-button>
                <el-button type="warning" plain icon="el-icon-download" size="mini"
                    @click="handleDetailedExport">明细表导出</el-button>
                <el-button type="warning" plain icon="el-icon-download" size="mini"
                    @click="handleSummaryExport">汇总表导出</el-button>
                <el-badge :value="main.yesterdayPaymentPendingCount" style="margin-left: 10px;">
                    <el-button type="primary" icon="el-icon-search" size="mini"
                        @click="getYesterdayPaymentPendingCount">昨日待支付数(点击检索)</el-button>
                </el-badge>
            </el-form-item>
        </el-form>
        <el-table v-loading="main.loading" :data="main.reserveRegisterList" style="width: 100%"
            @selection-change="handleSelectionChange" ref="reserveRegisterTable">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="订单号" width="200px">
                <template slot-scope="scope">
                    {{ scope.row.eOrderCode }} <br />
                    {{ scope.row.orderCode }}

                    <span v-if="scope.row.jzjPrice && scope.row.jzjPrice > 0">
                        <br>
                        <el-tag type="danger">有结转金</el-tag>
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="系统 / 接受订单时间" prop="handleTime" width="150px">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.platformName === '宝尚'" type="warning">{{ scope.row.platformName }}</el-tag>
                    <el-tag v-if="scope.row.platformName === '悦游'" type="success">{{ scope.row.platformName }}</el-tag>
                    <br />
                    {{ formattedDate1(scope.row.handleTime) }}
                </template>
            </el-table-column>
            <el-table-column label="销售单信息" width="100px">
                <template slot-scope="scope">
                    <div>
                        <el-tag v-if="scope.row.ddlx === '销售单'" type="success">{{ scope.row.ddlx }}</el-tag>
                        <el-tag v-else type="danger">{{ scope.row.ddlx }}</el-tag>
                    </div>

                    <div style="margin-top: 10px;">
                        <el-tag class="zfztClass" @click="openPaymentInfo(scope.row)" v-if="scope.row.zfzt === '已支付'"
                            type="success">已支付</el-tag>
                        <el-tag class="zfztClass" v-if="scope.row.zfzt === '待支付'" type="warning">待支付</el-tag>
                        <el-tag class="zfztClass" v-if="scope.row.zfzt === '无需支付'" type="info">无需支付</el-tag>
                        <el-tag class="zfztClass" @click="openPaymentInfo(scope.row)" v-if="scope.row.zfzt === '待返款'"
                            type="warning">待返款</el-tag>
                        <el-tag class="zfztClass" @click="openPaymentInfo(scope.row)" v-if="scope.row.zfzt === '已返款'"
                            type="success">已返款</el-tag>

                    </div>
                </template>
            </el-table-column>
            <el-table-column label="支付类型" prop="zflx" width="120px" />
            <el-table-column label="酒店信息" width="220px">
                <template slot-scope="scope">
                    宝尚ID：{{ scope.row.bsHotelId }} <br />
                    悦游ID：{{ scope.row.hotelId }} <br />
                    {{ scope.row.hotelName }}
                </template>
            </el-table-column>
            <el-table-column label="客人姓名" prop="names" />
            <el-table-column label="采购价">
                <template slot-scope="scope">
                    <span style="color: #1890ff;cursor: pointer;" @click="openEditCgj(scope.row)">{{
                        scope.row.cgjOriginal }}</span>
                </template>
            </el-table-column>
            <el-table-column label="入住日期">
                <template slot-scope="scope">
                    {{ formattedDate(scope.row.startTime) }}
                </template>
            </el-table-column>
            <el-table-column label="离店日期">
                <template slot-scope="scope">
                    {{ formattedDate(scope.row.endTime) }}
                </template>
            </el-table-column>

            <el-table-column label="是否有待返款" prop="dfkSum" width="100px">
                <template slot-scope="scope">
                    <div @click="openPaymentInfoAndRefundInfo(scope.row)">
                        <el-tag class="zfztClass" v-if="scope.row.dfkSum === 0" type="success">否</el-tag>
                        <el-tag class="zfztClass" v-if="scope.row.dfkSum === 1" type="warning">是</el-tag>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="支付日期" prop="paymentDate" width="150px">
                <template slot-scope="scope">
                    {{ formattedDate(scope.row.paymentDate) }}
                </template>
            </el-table-column>
            <el-table-column label="结算方式">
                <template slot-scope="scope">
                    <span v-if="scope.row.zffs === '预付款'" style="color: red;">{{ scope.row.zffs }}</span>
                    <span v-else>{{ scope.row.zffs }}</span><br />
                    {{ scope.row.jsfs }} <br />
                    {{ scope.row.jdjd }}
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="120px">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" @click="openEditPayment(scope.row)">编辑</el-button>
                    <el-button size="mini" type="text" @click="postCopyRegister(scope.row)">复制</el-button> <br />
                    <el-button size="mini" type="text" @click="postEmptyRegister(scope.row)">清空</el-button>
                    <el-button size="mini" type="text" @click="postDeleteRegister(scope.row)">删除</el-button>
                </template>
            </el-table-column>
            <template slot="append" v-if="summaryInfo">
                <div class="totalClass">
                    <span>支付汇总信息：</span>
                    采购价：<span class="totalText">{{ summaryInfo.cgjOriginal }}</span>支付总金额：<span class="totalText">{{
                        summaryInfo.paymentPrice }}</span>
                    返款总金额：<span class="totalText">{{ summaryInfo.refundPrice }}</span> 实际支付金额：<span class="totalText">{{
                        summaryInfo.sjzfje }}</span>
                    结算价：<span class="totalText">{{ summaryInfo.jsj }}</span>
                </div>
            </template>
        </el-table>
        <pagination v-show="main.reserveRegisterListTotal > 0" :total="main.reserveRegisterListTotal"
            :page.sync="main.queryParams.pageNum" :limit.sync="main.queryParams.pageSize"
            @pagination="getReserveRegisterList" />

        <el-dialog title="订单支付" :visible.sync="paymentInfo.isShow" width="1250px" append-to-body>
            <div>
                <div>
                    支付日期：<span style="color: brown;">{{ formattedDate(paymentInfo.paymentDate) }}</span>
                </div>
                <div style="margin-top: 10px;">支付类型：<span style="color: brown;">{{ paymentInfo.zflx }}</span></div>
                <div style="margin-top: 10px;">采购价总和：<span style="color: red;">￥{{ paymentInfo.cgjOriginalCount
                        }}</span>
                </div>
                <div style="margin-top: 10px;">
                    酒店待返款金额：<span style="color: red;">￥{{ paymentInfo.hotelDfk }}</span>
                </div>
                <div style="margin-top: 10px;">
                    酒店结转金余额：<span style="color: red;">￥{{ paymentInfo.hotelJzj }}</span>
                </div>

            </div>
            <el-table :data="paymentInfo.selectRegisterList" style="margin-top: 20px;" :key="paymentInfo.tableKey">
                <el-table-column label="系统单号" prop="orderCode" width="190px" />
                <el-table-column label="渠道单号" prop="eOrderCode" />
                <el-table-column label="客人姓名" prop="names" />
                <el-table-column label="采购价" prop="cgjOriginal" />
                <el-table-column label="状态" align="center" v-if="paymentInfo.showType === 'add'">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.addStatus" type="success">已添加支付记录</el-tag>
                        <el-tag v-else type="danger">未添加支付记录</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" v-if="paymentInfo.showType === 'add'">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" @click="addPayment(scope.row)">添加支付记录</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-table :data="paymentInfo.registerPaymentList" style="margin-top: 20px;">
                <el-table-column label="系统单号" prop="orderCode" width="200px" />
                <el-table-column label="支付渠道" prop="zfqd" width="200px" align="center">
                    <template slot="header">
                        <span>支付渠道 <span style="color: red;">*</span></span>
                    </template>
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.zfqd" placeholder="请选择支付渠道" clearable>
                            <el-option v-for="dict in dict.type.el_zfqd" :key="dict.value" :label="dict.label"
                                :value="dict.value"></el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="支付金额" prop="paymentPrice" width="210px" align="center">
                    <template slot="header">
                        <span>支付金额 <span style="color: red;">*</span></span>
                    </template>
                    <template slot-scope="scope">
                        <el-input-number :disabled="scope.row.id != null" v-model="scope.row.paymentPrice"
                            :min="0"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column label="实际支付日期" prop="paymentDateActual" width="210px" align="center">
                    <template slot="header">
                        <span>实际支付日期 <span style="color: red;">*</span></span>
                    </template>
                    <template slot-scope="scope">
                        <el-date-picker value-format="yyyy-MM-dd" style="width: 100%;"
                            v-model="scope.row.paymentDateActual" :disabled="scope.row.id != null" type="date"
                            placeholder="选择日期">
                        </el-date-picker>
                    </template>
                </el-table-column>
                <el-table-column label="录入人" prop="createName" width="140px" align="center" />
                <el-table-column label="备注" prop="remarks" width="250px" align="center">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.remarks"></el-input>
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button type="danger" @click="clearPayment">清空支付列表</el-button>
                <el-button type="primary" :loading="paymentInfo.loading" @click="postPayment">确 定</el-button>
                <el-button @click="closePayment">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog title="订单返款" :visible.sync="refundInfo.isShow" width="1240px" append-to-body>
            <el-table :data="refundInfo.refundHotelInfo" style="margin-top: 20px;" :key="refundInfo.tableKey">
                <el-table-column label="系统单号" prop="orderCode" width="190px" />
                <el-table-column label="渠道单号" prop="eOrderCode" width="170px" />
                <el-table-column label="客人姓名" prop="names" width="170px" />
                <el-table-column label="采购价" prop="cgjOriginal" />
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" @click="addRefund(scope.row)">添加返款记录</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-table :data="refundInfo.registerPaymentList" style="margin-top: 20px;">
                <el-table-column label="支付渠道" prop="zfqdLabel" width="200px" />
                <el-table-column label="支付金额" prop="paymentPrice" width="220px" />
                <el-table-column label="支付日期" prop="paymentDate" width="220px">
                    <template slot-scope="scope">
                        {{ formattedDate(scope.row.paymentDate) }}
                    </template>
                </el-table-column>
                <el-table-column label="备注" prop="remarks" width="560px" />
            </el-table>

            <el-table :data="refundInfo.registerRefundList" style="margin-top: 20px;">
                <el-table-column label="返款状态" prop="refundStatus" width="200px" align="center">
                    <template slot="header">
                        <span>返款状态 <span style="color: red;">*</span></span>
                    </template>
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.refundStatus" @change="refundStatusChange(scope.row)"
                            :disabled="scope.row.isDisabled === true && scope.row.refundStatus != '0'"
                            placeholder="请选择返款状态" clearable>
                            <el-option v-for="dict in dict.type.el_fkzt" :key="dict.value" :label="dict.label"
                                :value="dict.value"></el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="返款金额" prop="refundPrice" width="210px" align="center">
                    <template slot="header">
                        <span>返款金额 <span style="color: red;">*</span></span>
                    </template>
                    <template slot-scope="scope">
                        <el-input-number :disabled="scope.row.id != null" v-model="scope.row.refundPrice"
                            :min="0"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column label="返款渠道" prop="fkqd" width="220px" align="center">
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.fkqd" :disabled="scope.row.refundStatus === '0'"
                            placeholder="请选择返款渠道" @change="zfqdChange(scope.row)" clearable>
                            <el-option v-for="dict in dict.type.el_fkqd" :key="dict.value" :label="dict.label"
                                :value="dict.value"></el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="返款日期" prop="refundDate" width="220px" align="center">
                    <template slot-scope="scope">
                        <el-date-picker value-format="yyyy-MM-dd" :disabled="scope.row.isDisabled === true"
                            style="width: 100%;" v-model="scope.row.refundDate" type="date" placeholder="选择日期">
                        </el-date-picker>
                    </template>
                </el-table-column>
                <el-table-column label="录入人" prop="createName" width="140px" align="center" />
                <el-table-column label="备注" prop="remarks" width="210px" align="center">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.remarks" :disabled="scope.row.isChangeZfqd === false"></el-input>
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button type="danger" @click="clearRefund">清空返款记录</el-button>
                <el-button type="primary" :loading="refundInfo.loading" @click="postRefund">确 定</el-button>
                <el-button @click="closeRefund">取 消</el-button>
            </div>

        </el-dialog>

        <el-dialog title="修改" :visible.sync="editPayment.isShow" width="700px" append-to-body>
            <el-form ref="editPaymentForm" :rules="editPayment.rules" :model="editPayment.form" label-width="100px">
                <el-row>
                    <el-col :span="11">
                        <el-form-item prop="paymentDate" label="支付日期">
                            <el-date-picker value-format="yyyy-MM-dd" style="width: 100%;"
                                v-model="editPayment.form.paymentDate" type="date" placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item prop="registerType" label="销售单类型">
                            <el-select v-model="editPayment.form.registerType" placeholder="请选择销售单类型" clearable>
                                <el-option v-for="dict in dict.type.el_xsdlx" :key="dict.value" :label="dict.label"
                                    :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" :loading="editPayment.loading" @click="postEditPayment">确 定</el-button>
                <el-button @click="closeEditPayment">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog title="修改悦游采购价" :visible.sync="yueyouEditCgj.isShow" width="700px" append-to-body>
            <el-table :data="yueyouEditCgj.fjdj">
                <el-table-column label="日期" prop="rpPriceDay" />
                <el-table-column label="采购价" prop="rpPrice" align="center">
                    <template slot-scope="scope">
                        <el-input-number v-model="scope.row.rpPrice" :min="0"></el-input-number>
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" :loading="yueyouEditCgj.loading" @click="postYueYouEditCgj">确 定</el-button>
                <el-button @click="closeYueYouEditCgj">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog title="修改宝尚采购价" :visible.sync="baoShangEditCgj.isShow" width="700px" append-to-body>
            <el-form ref="baoShangEditCgjForm" :rules="baoShangEditCgj.rules" :model="baoShangEditCgj.form">
                <el-form-item prop="cgj" label="采购价">
                    <el-input-number v-model="baoShangEditCgj.form.cgj" :min="0"></el-input-number>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" :loading="baoShangEditCgj.loading" @click="postBaoShangEditCgj">确
                    定</el-button>
                <el-button @click="closeBaoShangEditCgj">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog title="登记表录入" :visible.sync="addRegister.isShow" width="800px" append-to-body>
            <el-form ref="addRegisterForm" :rules="addRegister.rules" :model="addRegister.form" label-width="110px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item prop="handleTime" label="订单处理时间">
                            <el-date-picker v-model="addRegister.form.handleTime" type="datetime" style="width: 100%;"
                                placeholder="选择日期时间">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item prop="platformName" label="系统">
                            <el-select v-model="addRegister.form.platformName" placeholder="请选择" class="form-item-width"
                                clearable>
                                <el-option label="宝尚" value="宝尚" key="宝尚"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item prop="hotelId" label="酒店">
                            <el-select v-model="addRegister.form.hotelId" filterable placeholder="请选择"
                                class="form-item-width" clearable>
                                <el-option v-for="item in main.hotelListAll" :key="item.hotelId" :label="item.hotelName"
                                    :value="item.hotelId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item prop="orderCode" label="供应商订单号">
                            <el-input v-model="addRegister.form.orderCode" placeholder="请输入供应商订单号" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item prop="eOrderCode" label="渠道订单号">
                            <el-input v-model="addRegister.form.eOrderCode" placeholder="请输入渠道订单号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item prop="names" label="客人姓名">
                            <el-input v-model="addRegister.form.names" placeholder="请输入客人姓名" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item prop="cgj" label="采购价">
                            <el-input-number v-model="addRegister.form.cgj" :min="0"
                                class="form-item-width"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item prop="startTime" label="入住日期">
                            <el-date-picker value-format="yyyy-MM-dd" style="width: 100%;"
                                v-model="addRegister.form.startTime" type="date" placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item prop="endTime" label="离店日期">
                            <el-date-picker value-format="yyyy-MM-dd" style="width: 100%;"
                                v-model="addRegister.form.endTime" type="date" placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item prop="fjsNum" label="房间数">
                            <el-input-number v-model="addRegister.form.fjsNum" :min="0"
                                class="form-item-width"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" :loading="addRegister.loading" @click="postAddRegister">确 定</el-button>
                <el-button @click="closeAddRegister">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getHotelListAll } from "@/api/hotel/hotel";
import {
    getReserveRegisterList, postPaymentInfo, postEditPaymentInfo, getOrderRegisterPayment, postRefundInfo,
    getOrderRegisterRefund, getHotelDfkPrice, getRegisterAndPaymentByBatchId, getReserveRegisterById, postAddRegister,
    postPaymentValid, postCopyRegister, postDeleteRegister, postEmptyRegister
} from "@/api/hotel/orderRegister";
import { getCgjByOrderId, postYueYouEditCgj } from "@/api/hotel/rp";
import { getYesterday } from "@/utils/timing-order";


export default {
    name: 'ReserveRegister',
    dicts: ['el_zfqd', 'el_zfzt', 'el_xsdlx', 'el_fkzt', 'el_fkqd'],
    data() {
        return {
            main: {
                loading: false,
                showSearch: true,
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    orderCode: undefined,
                    eOrderCode: undefined,
                    names: undefined,
                    hotelId: undefined,
                    paymentDate: [],
                    zfzt: undefined,
                    zfqd: undefined,
                    fkqd: undefined,
                    paymentPrice: undefined,
                    xsdlx: undefined,
                    refundStatus: undefined,
                    cgj: undefined,
                    startTime: [],
                    endTime: [],
                    refundDate: []
                },
                hotelListAll: [],
                reserveRegisterList: [],
                reserveRegisterListTotal: 0,
                yesterdayPaymentPendingCount: 0
            },
            editPayment: {
                isShow: false,
                loading: false,
                form: {
                    paymentDate: undefined,
                    registerId: undefined,
                    registerType: undefined
                },
                rules: {
                    paymentDate: [
                        { required: true, message: "请选择支付日期", trigger: "blur" },
                    ],
                    registerType: [
                        { required: true, message: "请选择销售单类型", trigger: "blur" },
                    ]
                }
            },
            paymentInfo: {
                registerId: undefined,
                isShow: false,
                loading: false,
                selectRegisterList: [],
                paymentDate: undefined,
                zflx: undefined,
                cgjOriginalCount: 0,
                hotelJzj: undefined,
                hotelDfk: undefined,
                registerPaymentList: [],
                tableKey: 1,
                hotelId: undefined,
                showType: undefined
            },
            refundInfo: {
                registerId: undefined,
                isShow: false,
                loading: false,
                refundHotelInfo: [],
                registerPaymentList: [],
                registerRefundList: [],
                tableKey: 1,
                hotelId: undefined
            },
            yueyouEditCgj: {
                orderId: undefined,
                isShow: false,
                fjdj: [],
                loading: false
            },
            baoShangEditCgj: {
                isShow: false,
                loading: false,
                form: {
                    id: undefined,
                    cgj: undefined
                },
                rules: {
                    cgj: [
                        { required: true, message: "请输入采购价", trigger: "blur" },
                    ]
                }
            },
            addRegister: {
                isShow: false,
                loading: false,
                rules: {
                },
                form: {
                    platformName: '宝尚'
                },
                rules: {
                    handleTime: [
                        { required: true, message: "请选择订单处理时间", trigger: "blur" },
                    ],
                    platformName: [
                        { required: true, message: "请选择系统", trigger: "blur" },
                    ],
                    hotelId: [
                        { required: true, message: "请选择酒店", trigger: "blur" },
                    ],
                    orderCode: [
                        { required: true, message: "请输入供应商订单号", trigger: "blur" },
                    ],
                    eOrderCode: [
                        { required: true, message: "请输入渠道订单号", trigger: "blur" },
                    ],
                    names: [
                        { required: true, message: "请输入客人姓名", trigger: "blur" },
                    ],
                    cgj: [
                        { required: true, message: "请输入采购价", trigger: "blur" },
                    ],
                    startTime: [
                        { required: true, message: "请输入入住日期", trigger: "blur" },
                    ],
                    endTime: [
                        { required: true, message: "请输入离店日期", trigger: "blur" },
                    ],
                    fjsNum: [
                        { required: true, message: "请输入房间数", trigger: "blur" },
                    ]
                }
            },
            summaryInfo: undefined
        }
    },
    created() {
        this.getHotelListAll();
        this.getReserveRegisterList();
    },
    methods: {
        // 获取所有酒店数据,用于酒店下拉框
        getHotelListAll() {
            getHotelListAll().then(response => {
                this.main.hotelListAll = response.data;
            }
            );
        },
        getReserveRegisterList() {
            this.main.loading = true;
            getReserveRegisterList(this.main.queryParams).then(response => {
                console.log(response);
                this.main.reserveRegisterList = response.data.reserveRegisterList.rows;
                this.main.reserveRegisterListTotal = response.data.reserveRegisterList.total;
                this.main.yesterdayPaymentPendingCount = response.data.yesterdayPaymentPendingCount;
                if (response.data.summaryInfo) {
                    this.summaryInfo = {}
                    this.summaryInfo.cgjOriginal = response.data.summaryInfo.cgjOriginal;
                    this.summaryInfo.paymentPrice = response.data.summaryInfo.paymentPrice;
                    this.summaryInfo.refundPrice = response.data.summaryInfo.refundPrice;
                    this.summaryInfo.sjzfje = response.data.summaryInfo.sjzfje;
                    this.summaryInfo.jsj = response.data.summaryInfo.jsj;
                    console.log(this.summaryInfo);
                } else {
                    this.summaryInfo = undefined;
                }
                this.main.loading = false;
            }
            );
        },
        handleQuery() {
            this.getReserveRegisterList();
        },
        handleSelectionChange(selection) {
            this.paymentInfo.selectRegisterList = selection;
        },
        openEditPayment(row) {
            this.editPayment.form.paymentDate = row.paymentDate;
            this.editPayment.form.registerId = row.id;
            this.editPayment.form.registerType = row.registerType + "";
            this.editPayment.form.zfzt = row.zfztVal;
            this.editPayment.isShow = true;
        },
        postEditPayment() {
            this.$refs["editPaymentForm"].validate(valid => {
                if (valid) {
                    this.editPayment.loading = true;
                    postEditPaymentInfo(this.editPayment.form).then(res => {
                        this.$modal.msgSuccess("修改成功");
                        this.editPayment.loading = false;
                        this.editPayment.isShow = false;
                        this.getReserveRegisterList();
                    });
                }

            })
        },
        closeEditPayment() {
            this.editPayment.isShow = false;
        },
        async openPayment() {
            try {
                // 初始化参数
                this.paymentInfo.registerPaymentList = [];
                this.paymentInfo.cgjOriginalCount = 0;
                this.paymentInfo.hotelJzj = 0;
                this.paymentInfo.hotelDfk = 0;
                this.paymentInfo.hotelId = undefined;
                this.paymentInfo.zflx = undefined;
                this.paymentInfo.paymentDate = undefined;
                this.paymentInfo.showType = 'add';

                // 获取已选中的数据
                const selectRegisterList = this.paymentInfo.selectRegisterList;

                // 校验是否选中
                if (selectRegisterList.length === 0) {
                    this.$message.error('请选择支付订单');
                    return;
                }

                // 校验订单状态、酒店是否一致、支付日期是否一致,这里去后端校验

                const res = await postPaymentValid(selectRegisterList);
                if (res.code === 200) {

                    // 通过校验,可以认定酒店id
                    this.paymentInfo.hotelId = res.data.hotelId;
                    // 通过校验,可以认定支付日期
                    this.paymentInfo.paymentDate = res.data.paymentDate;
                    this.paymentInfo.cgjOriginalCount = res.data.cgjOriginal;
                    if (res.data.hotelJzj) {
                        this.paymentInfo.hotelJzj = res.data.hotelJzj.jzjPrice;
                    } else {
                        this.paymentInfo.hotelJzj = res.data.hotelJzj;
                    }
                    this.paymentInfo.hotelDfk = res.data.hotelDfk;

                    for (let i = 0; i < this.paymentInfo.selectRegisterList.length; i++) {
                        this.paymentInfo.selectRegisterList[i].addStatus = undefined;
                    }

                    if (selectRegisterList.length > 1) {
                        // 支付类型为并单支付
                        this.paymentInfo.zflx = '并单支付';
                    } else {
                        // 支付类型为单独支付
                        this.paymentInfo.zflx = '单独支付';
                    }
                }
                this.paymentInfo.isShow = true;
            } catch (error) {
                // 处理可能发生的任何错误
                console.error('Error during payment validation:', error);
            }
        },
        closePayment() {
            this.paymentInfo.isShow = false;
        },
        addPayment(row) {
            row.addStatus = 1;
            this.paymentInfo.tableKey += 1;
            this.paymentInfo.registerPaymentList.push({ registerId: row.id, orderCode: row.orderCode });
        },
        clearPayment() {
            this.paymentInfo.registerPaymentList = [];
            for (let i = 0; i < this.paymentInfo.selectRegisterList.length; i++) {
                this.paymentInfo.selectRegisterList[i].addStatus = undefined;
            }
            this.paymentInfo.tableKey += 1;
        },

        /**
         * 主要是已经支付过的订单,回头又要修改支付渠道
         */
        openPaymentInfo(row) {
            this.paymentInfo.showType = 'edit';
            this.paymentInfo.paymentDate = undefined;
            this.paymentInfo.zflx = undefined;
            this.paymentInfo.cgjOriginalCount = 0;
            this.paymentInfo.hotelId = undefined;
            this.paymentInfo.hotelJzj = 0;
            this.paymentInfo.hotelDfk = 0;
            this.$refs.reserveRegisterTable.clearSelection();
            this.paymentInfo.selectRegisterList = [];
            getRegisterAndPaymentByBatchId({ registerId: row.id }).then(response => {
                this.paymentInfo.paymentDate = response.data.registerInfo.paymentDate;
                this.paymentInfo.zflx = response.data.registerInfo.paymentType;
                this.paymentInfo.selectRegisterList = response.data.orderList;
                this.paymentInfo.registerPaymentList = response.data.orderRegisterPaymentList;
                this.paymentInfo.hotelId = response.data.hotelId;
                const selectRegisterList = this.paymentInfo.selectRegisterList;
                for (let i = 0; i < selectRegisterList.length; i++) {
                    this.paymentInfo.cgjOriginalCount += selectRegisterList[i].cgjOriginal;
                }
                this.paymentInfo.registerId = row.id;
                if (response.data.hotelJzj) {
                    this.paymentInfo.hotelJzj = response.data.hotelJzj.jzjPrice;
                }

                if (response.data.hotelDfk) {
                    this.paymentInfo.hotelDfk = response.data.hotelDfk;
                }
                this.paymentInfo.isShow = true;
            }
            );
        },
        postPayment() {
            // 提交前验证 必填项,有结转金是否选了结转金,无结转金是否选了结转金,支付金额和采购价是否一致
            const registerPaymentList = this.paymentInfo.registerPaymentList;
            const selectRegisterList = this.paymentInfo.selectRegisterList;
            let zfjeTotal = 0;
            let jzjTotal = 0;
            if (this.paymentInfo.showType === 'add') {
                for (let i = 0; i < selectRegisterList.length; i++) {
                    if (!selectRegisterList[i].addStatus) {
                        this.$message.error('你有未添加支付记录的订单');
                        return;
                    }
                }
            }
            let isJzj = false;
            for (let i = 0; i < registerPaymentList.length; i++) {
                const obj = registerPaymentList[i]
                if (!obj.zfqd) {
                    this.$message.error('请选择支付渠道');
                    return;
                }

                if (!obj.paymentPrice) {
                    this.$message.error('请输入支付金额');
                    return;
                }

                if (!obj.paymentDateActual) {
                    this.$message.error('请输入实际支付日期');
                    return;
                }

                if (obj.zfqd === '4') {
                    isJzj = true;
                    jzjTotal += obj.paymentPrice;
                }
                zfjeTotal += obj.paymentPrice;
            }

            // 没问题的话验证支付金额是否等于采购价
            if (zfjeTotal != this.paymentInfo.cgjOriginalCount) {
                this.$message.error('支付金额与采购总额不一致');
                return;
            }

            // 可以校验结转金
            if (this.paymentInfo.hotelJzj > 0) {
                if (isJzj === true) {
                    if (jzjTotal > this.paymentInfo.hotelJzj) {
                        this.$message.error('使用结转金不能大于酒店剩余结转金金额');
                        return;
                    }
                } else {
                    this.$message.error('有结转金请使用结转金支付');
                    return;
                }
            } else {
                if (isJzj === true) {
                    this.$message.error('该酒店无结转金可用');
                    return;
                }
            }
            // 提交
            let that = this;
            this.$modal.confirm('是否提交支付信息？').then(function () {
                const obj = {};
                that.paymentInfo.loading = true;
                obj.data = JSON.stringify(registerPaymentList);
                obj.hotelId = that.paymentInfo.hotelId;
                obj.zflx = that.paymentInfo.zflx;
                obj.showType = that.paymentInfo.showType;
                obj.paymentDate = that.paymentInfo.paymentDate;
                return postPaymentInfo(obj);
            }).then((res) => {
                if (res.code === 200) {
                    that.$modal.msgSuccess("操作成功");
                    that.paymentInfo.loading = false;
                    that.paymentInfo.isShow = false;
                    that.getReserveRegisterList();
                }
            }).catch((error) => {

            }).finally(() => {
                that.paymentInfo.loading = false;
            });
        },
        openPaymentInfoAndRefundInfo(row) {
            if (row.zfzt != '已支付' && row.zfzt != '待返款' && row.zfzt != '已返款') {
                return;
            }
            // 初始化数据
            this.refundInfo.refundHotelInfo = [];
            this.refundInfo.registerRefundList = [];
            this.refundInfo.hotelId = row.hotelId;
            let refundHotelInfo = {};
            refundHotelInfo.registerId = row.id;
            refundHotelInfo.orderCode = row.orderCode;
            refundHotelInfo.eOrderCode = row.eOrderCode;
            refundHotelInfo.names = row.names;
            refundHotelInfo.cgjOriginal = row.cgjOriginal;
            this.refundInfo.refundHotelInfo.push(refundHotelInfo);
            // 查一下这个订单的支付记录
            getOrderRegisterPayment({ registerId: row.id }).then(response => {
                this.refundInfo.registerPaymentList = response.data;
            }
            );

            // 查一下这个订单的返款记录
            getOrderRegisterRefund({ registerId: row.id }).then(response => {
                this.refundInfo.registerRefundList = response.data;
                for (let i = 0; i < this.refundInfo.registerRefundList.length; i++) {
                    if (this.refundInfo.registerRefundList[i].id) {
                        this.refundInfo.registerRefundList[i].isDisabled = true;
                        this.refundInfo.registerRefundList[i].isChangeZfqd = false;
                    }
                }
            }
            );
            this.refundInfo.registerId = row.id;
            this.refundInfo.isShow = true;
        },
        refundStatusChange(row) {
            if (row.refundStatus === '1') {
                row.isDisabled = false;
            } else if (row.refundStatus === '0') {
                row.fkqd = undefined;
                row.refundDate = undefined;
                row.isDisabled = true;
            }
        },
        zfqdChange(row) {
            row.isChangeZfqd = true;
            console.log(this.refundInfo.registerRefundList);
        },
        addRefund(row) {
            this.refundInfo.registerRefundList.push({ registerId: row.registerId });
        },
        clearRefund() {
            // 清除没有id属性的元素
            this.refundInfo.registerRefundList = this.refundInfo.registerRefundList.filter(item => 'id' in item);

        },
        postRefund() {
            const registerRefundList = this.refundInfo.registerRefundList;
            for (let i = 0; i < registerRefundList.length; i++) {
                const obj = registerRefundList[i]
                if (!obj.refundStatus) {
                    this.$message.error('请选择返款状态');
                    return;
                }

                if (!obj.refundPrice) {
                    this.$message.error('请填写返款金额');
                    return;
                }

                if (obj.refundStatus === '1') {
                    if (!obj.fkqd) {
                        this.$message.error('请选择返款渠道');
                        return;
                    }

                    if (!obj.refundDate) {
                        this.$message.error('请选择返款日期');
                        return;
                    }
                }
            }

            // 提交
            let that = this;
            this.$modal.confirm('是否提交返款信息？').then(function () {
                const obj = {};
                that.refundInfo.loading = true;
                obj.data = JSON.stringify(registerRefundList);
                obj.hotelId = that.refundInfo.hotelId;
                obj.registerId = that.refundInfo.registerId;
                return postRefundInfo(obj);
            }).then((res) => {
                if (res.code === 200) {
                    that.$modal.msgSuccess("操作成功");
                    that.refundInfo.loading = false;
                    that.refundInfo.isShow = false;
                    that.getReserveRegisterList();
                }
            }).catch((error) => {

            }).finally(() => {
                that.refundInfo.loading = false;
            });
        },
        closeRefund() {
            this.refundInfo.isShow = false;
        },
        openEditCgj(row) {
            if (row.platformName === '悦游') {
                getCgjByOrderId(row).then((res) => {
                    if (res.code === 200) {
                        this.yueyouEditCgj.orderId = row.orderId;
                        this.yueyouEditCgj.fjdj = res.data;
                        this.yueyouEditCgj.isShow = true;
                    }
                })
            } else {
                getReserveRegisterById({ id: row.id }).then((res) => {
                    if (res.code === 200) {
                        this.baoShangEditCgj.form.id = row.id;
                        this.baoShangEditCgj.form.cgj = res.data.cgj;
                        this.baoShangEditCgj.isShow = true;
                    }
                })
            }
        },
        postYueYouEditCgj() {
            for (let i = 0; i < this.yueyouEditCgj.fjdj.length; i++) {
                if (!this.yueyouEditCgj.fjdj[i].rpPrice) {
                    this.$message.error('请输入采购价');
                    return;
                }
            }
            postYueYouEditCgj({ fjdj: this.yueyouEditCgj.fjdj, orderId: this.yueyouEditCgj.orderId }).then((res) => {
                this.yueyouEditCgj.loading = true;
                if (res.code === 200) {
                    this.$modal.msgSuccess("操作成功");
                    this.yueyouEditCgj.isShow = false;
                    this.getReserveRegisterList();
                }
                this.yueyouEditCgj.loading = false;
            })
        },
        closeYueYouEditCgj() {
            this.yueyouEditCgj.isShow = false;
        },
        postBaoShangEditCgj() {
            console.log(this.baoShangEditCgj.form);
            this.$refs["baoShangEditCgjForm"].validate(valid => {
                if (valid) {
                    this.baoShangEditCgj.loading = true;
                    postEditPaymentInfo({ registerId: this.baoShangEditCgj.form.id, cgj: this.baoShangEditCgj.form.cgj }).then(res => {
                        this.$modal.msgSuccess("修改成功");
                        this.baoShangEditCgj.loading = false;
                        this.baoShangEditCgj.isShow = false;
                        this.getReserveRegisterList();
                    });
                }
            })
        },
        closeBaoShangEditCgj() {
            this.baoShangEditCgj.isShow = false;
        },
        openAddRegister() {
            this.addRegister.isShow = true;
        },
        postAddRegister() {
            this.$refs["addRegisterForm"].validate(valid => {
                if (valid) {
                    this.addRegister.form.handleTime = this.formattedDate2(this.addRegister.form.handleTime);
                    console.log(this.addRegister.form);
                    postAddRegister(this.addRegister.form).then(res => {
                        if (res.code === 200) {
                            this.$modal.msgSuccess("操作成功");
                            this.addRegister.isShow = false;
                            this.getReserveRegisterList();
                        }
                    });
                }
            })
        },
        closeAddRegister() {
            this.addRegister.isShow = false;
        },
        handleDetailedExport() {
            let queryParams = this.main.queryParams;
            delete queryParams.pageNum;
            delete queryParams.pageSize;
            this.download('hotel/order/register/handleDetailedExport', queryParams, `登记表明细_${new Date().getTime()}.xlsx`)
        },
        handleSummaryExport() {
            let queryParams = this.main.queryParams;
            delete queryParams.pageNum;
            delete queryParams.pageSize;
            this.download('hotel/order/register/handleSummaryExport', queryParams, `登记表汇总_${new Date().getTime()}.xlsx`)
        },
        postCopyRegister(row) {
            let that = this;
            this.$modal.confirm('是否复制该条数据？').then(function () {
                return postCopyRegister(row);
            }).then((res) => {
                if (res.code === 200) {
                    that.$modal.msgSuccess("操作成功");
                    that.getReserveRegisterList();
                }
            })
        },
        postDeleteRegister(row) {
            let that = this;
            this.$modal.confirm('是否删除该条数据？').then(function () {
                return postDeleteRegister(row);
            }).then((res) => {
                if (res.code === 200) {
                    that.$modal.msgSuccess("操作成功");
                    that.getReserveRegisterList();
                }
            })
        },
        postEmptyRegister(row) {
            let that = this;
            this.$modal.confirm('是否清空该条数据？').then(function () {
                return postEmptyRegister(row);
            }).then((res) => {
                if (res.code === 200) {
                    that.$modal.msgSuccess("操作成功");
                    that.getReserveRegisterList();
                }
            })
        },
        getYesterdayPaymentPendingCount() {
            this.main.queryParams.pageNum= 1;
            this.main.queryParams.pageSize=10;
            this.main.queryParams.orderCode= undefined;
            this.main.queryParams.eOrderCode= undefined;
            this.main.queryParams.names= undefined;
            this.main.queryParams.hotelId= undefined;
            const yestDay = getYesterday();
            this.main.queryParams.paymentDate=  [yestDay, yestDay];
            this.main.queryParams.zfzt= "2";
            this.main.queryParams.zfqd= undefined;
            this.main.queryParams.fkqd= undefined;
            this.main.queryParams.paymentPrice= undefined;
            this.main.queryParams.xsdlx= "0";
            this.main.queryParams.refundStatus= undefined;
            this.main.queryParams.cgj= undefined;
            this.main.queryParams.startTime= [];
            this.main.queryParams.endTime= [];
            this.main.queryParams.refundDate= [];
            this.getReserveRegisterList();
        },
        clearQueryParams(){
            this.main.queryParams.pageNum= 1;
            this.main.queryParams.pageSize=10;
            this.main.queryParams.orderCode= undefined;
            this.main.queryParams.eOrderCode= undefined;
            this.main.queryParams.names= undefined;
            this.main.queryParams.hotelId= undefined;
            this.main.queryParams.paymentDate=  [];
            this.main.queryParams.zfzt= undefined;
            this.main.queryParams.zfqd= undefined;
            this.main.queryParams.fkqd= undefined;
            this.main.queryParams.paymentPrice= undefined;
            this.main.queryParams.xsdlx= undefined;
            this.main.queryParams.refundStatus= undefined;
            this.main.queryParams.cgj= undefined;
            this.main.queryParams.startTime= [];
            this.main.queryParams.endTime= [];
            this.main.queryParams.refundDate= [];
            this.getReserveRegisterList();
        }
    },
    computed: {
        formattedDate() {
            return function (date) {
                if (date) {
                    return date.replace(/T/g, ' ').replace(' 00:00:00', '').trim();
                } else {
                    return null;
                }
            };
        },
        formattedDate1() {
            return function (date) {
                if (date) {
                    return date.replace(/T/g, ' ').trim();
                } else {
                    return null;
                }
            };
        },
        formattedDate2() {
            return function (val) {
                if (val) {
                    const date = new Date(val);
                    return `${String(date.getFullYear()).padStart(4, '0')}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
                } else {
                    return null;
                }
            };
        }
    }
}
</script>

<style>
.zfztClass {
    cursor: pointer;
}

.form-item-width {
    width: 100%;
}

.totalClass {
    padding-top: 20px;
    padding-bottom: 20px;
    padding-left: 20px;
    font-size: 14px;
    background-color: #dfe6ec;
}

.totalText {
    color: #F56C6C;
    font-weight: bold;
    padding-right: 15px;
}
</style>